package fun.codedesign.datasource.spring.boot.autoconfigure;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;


@Configuration
@EnableConfigurationProperties({DataSourceProperties.class, TenantProperties.class})
public class TenantDatasourceAutoConfiguration {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Autowired
    private TenantProperties tenantProperties;

    @Bean
    @ConditionalOnClass(HikariDataSource.class)
    public DataSource dataSource() {
        TenantDataSource dataSource = new TenantDataSource();
        HikariDataSource dataSource1 = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        if (StringUtils.hasText(dataSourceProperties.getName())) {
            dataSource1.setPoolName(dataSourceProperties.getName());
        }

        dataSource.add(TenantContextHolder.DEFAULT_DATASOURCE, dataSource1);

        HikariDataSource dataSource2 = tenantProperties.getDatasourceList().get(0).initializeDataSourceBuilder().type(HikariDataSource.class).build();

        // TODO 初始化第二个datasource2即可
        dataSource.add(TenantContextHolder.TENANT_DATASOURCE, dataSource2);
        return dataSource;
    }
}